<template>
  <a-card title="客户查询" :bordered="false" class="condition-card">
    <div class="condition-row">
      <div class="condition-col flex align-center justify-between">
        <div class="input-box flex align-center">
          <span class="label mr-20">账号</span>
          <a-input allow-clear placeholder="请输入账号" v-model:value="conditionState.userName"></a-input>
        </div>
        <a-button class="ml-20" type="primary" :loading="searchLoading" @click="handleSearch">查询</a-button>
      </div>
    </div>
  </a-card>
  <a-card title="客户列表" :bordered="false" class="result-card mt-20">
    <a-table :columns="columns" :data-source="userList" :pagination="false" :scroll="{y: 'calc(100vh - 405px)'}">
      <template #bodyCell="{record, column}">
        <template v-if="column.dataIndex === 'option'">
          <a-button type="link" @click="handlePopRechargeModal(record)" v-authOperate="'operate-recharge'">充值</a-button>
        </template>
      </template>
    </a-table>
    <div class="pagination-content flex justify-end">
      <a-pagination v-model:current="conditionState.page" show-quick-jumper show-size-changer :show-total="total => `共 ${total} 条`" :total="total" v-model:pageSize="conditionState.size" @change="handlePageChange" />
    </div>
  </a-card>
  <a-modal :width="320" title="客户充值" v-model:visible="modalVisible" :confirmLoading="saveLoading" @ok="handleSaveRecharge">
    <p>正在给客户：【{{currentUserName}}】 充值</p>
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="formRef">
      <a-form-item
          label="充值金额"
          name="amount">
        <a-input-number style="width: 100%;" v-model:value="formState.amount" :min="0.1" :max="9999999" placeholder="请输入金额"></a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {reactive, ref, nextTick} from "vue";
import api from '../../api/users'
import {UserItem} from '../../types/common'
import {UserTypes, UserTypesObj, UserSex} from '../../common/constants'
import {formatDateTime, uuid} from '../../common/utils'
import {message} from "ant-design-vue";
const searchLoading = ref<boolean>(false)
const conditionState = reactive({
  userName: '',
  userType: UserTypesObj.client.code,
  page: 1,
  size: 10,
})
const total = ref<number>(0)
const userList = ref<UserItem[]>([])
const columns = [
  {
    dataIndex: 'userName',
    key: 'userName',
    title: '账号',
  },{
    dataIndex: 'createdDate',
    key: 'createdDate',
    title: '创建时间',
  },{
    dataIndex: 'lastLoginTime',
    key: 'lastLoginTime',
    title: '最后登录',
  },{
    dataIndex: 'option',
    key: 'option',
    title: '操作',
  },
]
const getPageData = async () => {
  searchLoading.value = true
  userList.value = []
  try {
    const res = await api.getList({
      userName: conditionState.userName || '',
      userType: conditionState.userType || '',
      page: conditionState.page - 1,
      size: conditionState.size,
    })
    searchLoading.value = false
    if (res.content) {
      total.value = res.content.total || 0
      if (res.content.content && res.content.content.length) {
        res.content.content.forEach((user: UserItem) => {
          user.createdDate = formatDateTime(new Date(user.createdDate))
          user.lastLoginTime = user.lastLoginTime ? formatDateTime(new Date(user.lastLoginTime)) : ''
        })
        userList.value = res.content.content
      }
    }
  } catch(e: any) {
    searchLoading.value = false
  }
}
const handleSearch = () => {
  conditionState.page = 1
  total.value = 0
  getPageData()
}
const handlePageChange = (page: number, pageSize: number) => {
  if (pageSize !== conditionState.size) {
    conditionState.page = 1
  }
  getPageData()
}
handleSearch()
const modalVisible = ref(false)
const formRef = ref()
const rules = {
  amount: [
    { required: true, trigger: 'blur', message: '请输入充值金额' },
  ],
}
const formState = ref({
  amount: 0.1,
  userName: ''
})
const saveLoading = ref<boolean>(false)
const currentUserName = ref('')
const handlePopRechargeModal = (record: UserItem) => {
  formState.value.userName = record.userName
  formState.value.amount = 0.1
  currentUserName.value = record.userName
  modalVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
const handleSaveRecharge = async () => {
  if (formState.value.amount)
  try {
    await formRef.value.validateFields()
    console.log('formState', formState.value)
    saveLoading.value = true
    const res = await api.recharge({
      userName: formState.value.userName,
      amount: formState.value.amount
    })
    saveLoading.value = false
    if (res.success) {
      message.success('充值成功')
      modalVisible.value = false
    } else {
      let msg = '充值失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  }catch(e){
    saveLoading.value = false
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
</script>

<style scoped lang="less">
.condition-col{
  .ant-input{
    min-width: 300px;
  }
  .ant-select{
    min-width: 160px;
  }
  .ant-input-affix-wrapper{
    width: 200px;
  }
}
.ant-btn-link{
  padding: 0;
}
</style>
